package net.rcan.android.sample.rest;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	Button getButton;
	TextView testView;
	Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_activity);
		init_ui();
		init_event();
		context = this;
	}

	private void init_event() {

		getButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				new Thread(new Runnable() {

					@Override
					public void run() {
						HttpClient httpclient = new DefaultHttpClient();
						HttpResponse response = null;
						HttpEntity entity = null;
						BufferedReader br = null;
						String line = null;
						String line_all = "";

						HttpRequestBase httpBase = null;

						HttpGet httpReq = new HttpGet(
								"http://테스트주소:8080/Sample/test");
						httpBase = httpReq;

						try {
							response = httpclient.execute(httpBase);
							entity = response.getEntity();

							try {

								br = new BufferedReader(new InputStreamReader(
										entity.getContent()));

								while ((line = br.readLine()) != null) {
									line_all += line;
								}
							} finally {
								if (br != null)
									try {
										br.close();
									} catch (Exception e) {
									}

							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						final String testSTring = line_all;
						((Activity) context).runOnUiThread(new Runnable() {

							@Override
							public void run() {

								testView.setText(testSTring);
							}
						});

					}
				}).start();

			}
		});
	}

	private void init_ui() {
		getButton = (Button) findViewById(R.id.button1);
		testView = (TextView) findViewById(R.id.textView1);

	}

}
